package cn.com.bluemoon.daps.model.service.impl;

import cn.com.bluemoon.daps.common.domain.ResultBean;
import cn.com.bluemoon.daps.model.entity.DapDataModel;
import cn.com.bluemoon.daps.model.entity.DapDataModelFieldRenameRecord;
import cn.com.bluemoon.daps.model.entity.DapDataModelTableField;
import cn.com.bluemoon.daps.model.mapper.DapDataModelFieldRenameRecordMapper;
import cn.com.bluemoon.daps.model.mapper.DapDataModelMapper;
import cn.com.bluemoon.daps.model.service.DapDataModelFieldRenameRecordService;
import cn.com.bluemoon.daps.model.service.DapDataModelService;
import cn.com.bluemoon.daps.model.service.DapDataModelTableFieldService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


@Slf4j
@Service
public class DapDataModelFieldRenameRecordServiceImpl extends ServiceImpl<DapDataModelFieldRenameRecordMapper, DapDataModelFieldRenameRecord> implements DapDataModelFieldRenameRecordService {

    @Resource
    DapDataModelTableFieldService dapDataModelTableFieldService;

    @Override
    public void fieldIsRename(List<DapDataModelTableField> fieldList) {

        // 过滤出修改的数据
        List<DapDataModelTableField> modifyFields = fieldList.stream().filter(f -> StringUtils.isNotBlank(f.getId())).collect(Collectors.toList());
        if(!modifyFields.isEmpty()){
            DapDataModelTableField dapDataModelTableField = modifyFields.stream().findFirst().get();
            String modelTableId = dapDataModelTableField.getModelTableId();// 表id
            String dataModelId = dapDataModelTableField.getDataModelId();// 模型id
            List<String> modifyIds = modifyFields.stream().map(DapDataModelTableField::getId).collect(Collectors.toList());
            // 查询字段 旧字段
            List<DapDataModelTableField> oldFields = dapDataModelTableFieldService.getBaseMapper().selectBatchIds(modifyIds);
            // 新字段名
            Map<String, String> map = modifyFields.stream().collect(Collectors.toMap(DapDataModelTableField::getId, DapDataModelTableField::getFieldName));
            Map<String, List<String>> newAndOldFieldNames = oldFields.stream().filter(o -> map.containsKey(o.getId()) && !(map.get(o.getId()).equals(o.getFieldName())))
                    .collect(Collectors.toMap(o -> o.getId(),o -> Arrays.asList(map.get(o.getId()), o.getFieldName())));
            // 记录字段
            if (!newAndOldFieldNames.isEmpty()){
                List<DapDataModelFieldRenameRecord> recordList = Lists.newArrayList();
                List<String> ids = new ArrayList<>(newAndOldFieldNames.keySet());
                LambdaQueryWrapper<DapDataModelFieldRenameRecord> in = new LambdaQueryWrapper<DapDataModelFieldRenameRecord>().in(DapDataModelFieldRenameRecord::getFieldId, ids);
                List<DapDataModelFieldRenameRecord> dataModelFieldRenameRecords = getBaseMapper().selectList(in);
                Map<String, List<String>> recordMap = dataModelFieldRenameRecords.stream().collect(Collectors.toMap(o -> o.getFieldId(), o -> Arrays.asList(o.getId(), o.getOldFieldName())));
                for (Map.Entry<String, List<String>> entry : newAndOldFieldNames.entrySet()) {
                    DapDataModelFieldRenameRecord record = new DapDataModelFieldRenameRecord();
                    List<String> value = entry.getValue();
                    record.setModelId(dataModelId);
                    record.setTableId(modelTableId);
                    record.setNewFieldName(value.stream().findFirst().get());
                    record.setOldFieldName(value.get(value.size()-1));
                    record.setFieldId(entry.getKey());
                    if(!recordMap.isEmpty() && recordMap.containsKey(entry.getKey())){
                        List<String> option = recordMap.get(entry.getKey());
                        record.setId(option.stream().findFirst().get());
                        record.setOldFieldName(option.get(option.size()-1));
                    }
                    recordList.add(record);
                }
                this.saveOrUpdateBatch(recordList);
            }
        }
    }

    /**
     * 查询改名记录
     * @param tableId
     * @param fieldId
     * @return
     */
    @Override
    public ResultBean<List<DapDataModelFieldRenameRecord>> getRenameRecord(String tableId, String fieldId) {

        LambdaQueryWrapper<DapDataModelFieldRenameRecord> wapper = new LambdaQueryWrapper<>();
        wapper.eq(DapDataModelFieldRenameRecord::getTableId, tableId);
        if(StringUtils.isNotBlank(fieldId)){
            wapper.eq(DapDataModelFieldRenameRecord::getFieldId, fieldId);
        }
        List<DapDataModelFieldRenameRecord> recordList = this.getBaseMapper().selectList(wapper);
        return ResultBean.ok(recordList);
    }

    /**
     *
     * @param tableId
     * @param fieldId
     * @return
     */
    @Override
    public void deleteRenameRecord(String tableId, String fieldId) {

        LambdaQueryWrapper<DapDataModelFieldRenameRecord> wappers = new LambdaQueryWrapper<>();
        wappers.eq(DapDataModelFieldRenameRecord::getTableId, tableId);
        if(StringUtils.isNotBlank(fieldId)){
            wappers.eq(DapDataModelFieldRenameRecord::getFieldId, fieldId);
        }
        this.getBaseMapper().delete(wappers);
    }
}
